require "utils"
module(..., package.seeall)
-- 初始化并打开I2C操作
-- @param I2C 内部ID
-- @return number ,I2C的速率
local function i2c_open(id, speed)
    if i2c.setup(id, speed or i2c.SLOW) ~= i2c.SLOW then
        i2c.close(id)
        return i2c.setup(id, speed or i2c.SLOW)
    end
    return i2c.SLOW
end

--- 读取SHT21的数据
-- @number id, 端口号0-2
-- @return string，string，第一个参数是温度，第二个是湿度
-- @usage tmp, hum = read()
function sht30(id, addr)
    local _, tmp, hum
    id, addr = id or 0, addr or 0x44
    -- if not i2c_open(id) then return end
    log.info("-------->I2C OPEN Result:", i2c_open(id))
    i2c.send(id, addr, {0x00, 0x06})
    i2c.send(id, addr, {0x2C, 0x06})
    _, tmp, _, hum, _ = pack.unpack(i2c.recv(id, addr, 6), '>HbHb')
    i2c.close(id)
    if tmp == nil or hum == nil then return end
    tmp, hum = 175 * tmp / 65535 - 45, 100 * hum / 65535
    if tmp > 120 or tmp < -40 then return end
    tmp, hum = string.format("%0.1f", tmp), string.format("%0.1f", hum)
    log.info("当前温度是:", tmp, "当前湿度是:", hum .. "%")
    return tmp, hum
end
function reset(id, addr)
    id, addr = id or 0, addr or 0x44
    if not i2c_open(id, i2c.SLOW) then return end
    i2c.send(id, addr, {0x00, 0x06})
    i2c.close(id)
end
local KXTJ3_ADDR = 0x0E
function readRegister(id, addr, reg)
    log.info("-------->I2C OPEN Result:", i2c_open(id))
    i2c.send(id, addr, reg)
    local _, tmp = pack.unpack(i2c.recv(id, addr, 1), 'b')
    i2c.close(id)
    return tmp;
end
function dcst(void)
    local val = readRegister(0, KXTJ3_ADDR, 0x0c)
    log.info("-------->KXTJ3C DCST Result:", val)
    return val;
end
KXTJ3_CTRL_REG1 = 0x1B
function writeReg(id, addr, reg, ...)
    log.info("-------->I2C OPEN Result:", i2c_open(id))
    i2c.send(id, addr, KXTJ3_CTRL_REG1)
    local _, regval = pack.unpack(i2c.recv(id, addr, 1), 'b')
    log.info("KXTJ3_CTRL_REG1 原始值:", regval)
    local std = bit.clear(regval, 7)
    log.info("KXTJ3_CTRL_REG1 写入值:", std)
    i2c.send(id, addr, {KXTJ3_CTRL_REG1, std})
    _, tmp = pack.unpack(i2c.recv(id, addr, 1), 'b')
    log.info("KXTJ3_CTRL_REG1 当前值:", tmp)
    i2c.send(id, addr, {reg, ...})
    _, tmp = pack.unpack(i2c.recv(id, addr, 2), '>H')
    log.info("用户写入寄存器 当前值:", tmp)
    std = bit.set(regval, 7)
    i2c.send(id, addr, {KXTJ3_CTRL_REG1, std})
    _, tmp = pack.unpack(i2c.recv(id, addr, 2), 'b')
    log.info("KXTJ3_CTRL_REG1 当前值:", tmp)
    i2c.close(id)
end
